package edu.zzuli.test.service.impl;

import edu.zzuli.test.service.UploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by Chen-D.W on 2018/3/5.
 */
@Service("uploadServiceImpl")
public class UploadServiceImpl implements UploadService{

    @Override
    public String uploadImage(CommonsMultipartFile file, String uploadPath, String realUploadPath) {

        InputStream is=null;

        OutputStream os=null;

        try {

            is=file.getInputStream();
            /**
             *保存到服务器的路径
             */
            String des=realUploadPath+"/"+file.getOriginalFilename();

            os=new FileOutputStream(des);

            byte[] buffer=new byte[1024];

            int len=0;

            while ((len=is.read(buffer))>0){
                os.write(buffer);
            }
        } catch (Exception e) {

            e.printStackTrace();

        } finally {
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return uploadPath+"/"+file.getOriginalFilename();
    }
}
